import type { AdColumn } from '@/components/AdTable';
import type { AdSearchFormActionType, AdSearchFormProps } from '@/components/AdTable/src/types/adSearchForm';

import type { ComputedRef } from 'vue';

import type { AdListProps } from '../types/adList';

import { computed, onUnmounted, ref, unref } from 'vue';

import { isProdMode } from '@eacloud/utils';

import { FilterGroup } from '#/request';

export function useAdSearchForm(propsRef: ComputedRef<AdListProps>, getLoading: ComputedRef<boolean | undefined>) {
  const formRef = ref<Nullable<AdSearchFormActionType>>(null);

  /** 注册 */
  function register(instance: AdSearchFormActionType) {
    isProdMode() &&
      onUnmounted(() => {
        formRef.value = null;
      });
    if (isProdMode() && instance === unref(formRef)) return;

    formRef.value = instance;
  }

  /** 方法 */
  const methods: AdSearchFormActionType = {
    /** 获取搜索信息 */
    getSearchInfo: () => {
      return unref(formRef)?.getSearchInfo() as FilterGroup;
    },
  };

  /** 搜索窗体属性 */
  const getSearchFormProps = computed((): Partial<AdSearchFormProps> => {
    const { searchForm, columns } = unref(propsRef);
    if (!searchForm) {
      return {};
    }
    const { autoSubmitOnEnter, submitOnReset, submitButtonOptions } = searchForm;
    return {
      submitButtonOptions: { loading: unref(getLoading), ...submitButtonOptions },
      compact: true,
      autoSubmitOnEnter,
      submitOnReset,
      columns: columns
        ? (columns.filter((item) => {
            // !调用filter方法，传入函数，若函数返回值为真，则返回该项，数组列不允许设置搜索
            // console.log(index);
            return item?.filterable === true && item?.dataType !== 'array';
          }) as AdColumn[])
        : [],
    };
  });

  return { getSearchFormProps, register, methods };
}
